using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Forms;
using System.Drawing;

using MyCollections.Model;

namespace MyCollections.Utils
{
    public class ImdbTools
    {
        private static string url_webservice = "http://www.trynt.com/movie-imdb-api/v2/";
        public ImdbTools()
        { }

        public static Imdb getImdbInfo(string title)
        {
            try
            {
                /* get id from imdb */
                string id = getImdbId(title);
                return getImdbInfoById(id);
            }
            catch (Exception ex)
            {
                //throw;
                return null;
            }
        }

        public static Imdb getImdbInfoById(string id)
        {   
            Imdb movie = new Imdb();

            try
            {
                /* connect to webservice and get data in xml */
                /* http://www.trynt.com/movie-imdb-api/v2/?i=tt0478087&u=&fo=xml&f=0 */
                string url = url_webservice + "?i=" + id + "&u=&fo=xml&f=0";
                string rsp = connectUrl(url);
                //string rsp = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<trynt>\n  <movie-imdb>\n    <title>21</title>\n    <aka></aka>\n    <year>2008</year>\n    <director></director>\n    <writer></writer>\n    <tagline></tagline>\n    <plot></plot>\n    <certification>\n      <New-Zealand>M</New-Zealand>\n      <Hong-Kong>IIB</Hong-Kong>\n      <Ireland>12A</Ireland>\n      <South-Africa>13V</South-Africa>\n      <Brazil>14</Brazil>\n      <USA>PG-13</USA>\n      <Italy>T</Italy>\n      <Canada>PG</Canada>\n      <Philippines>R-13</Philippines>\n      <South-Korea>15</South-Korea>\n      <Sweden>11</Sweden>\n      <Iceland>12</Iceland>\n      <Poland>15</Poland>\n      <Netherlands>12</Netherlands>\n      <UK>12A</UK>\n      <Switzerland>14</Switzerland>\n      <Argentina>13</Argentina>\n      <Germany>12</Germany>\n      <Australia>M</Australia>\n      <Greece>K-13</Greece>\n      <Singapore>PG</Singapore>\n      <Finland>K-13</Finland>\n    </certification>\n    <user-rating></user-rating>\n    <user-comment></user-comment>\n    <language></language>\n    <color></color>\n    <sound></sound>\n    <country></country>\n    <picture-url>http://ia.media-imdb.com/images/M/MV5BNzg0NzQyMzYzNl5BMl5BanBnXkFtZTcwODgyMjU1MQ@@._V1._SX100_SY139_.jpg</picture-url>\n    <runtime-min></runtime-min>\n    <trivia></trivia>\n    <goof></goof>\n    <award></award>\n    <genre>\n      <data>Drama</data>\n      <data>Drama</data>\n      <data>Drama</data>\n    </genre>\n    <actor></actor>\n    <url>http://www.imdb.com/title/tt0478087/</url>\n  </movie-imdb>\n<cache>true</cache></trynt>\n";

                rsp = rsp.Replace("<trynt>", "");
                rsp = rsp.Replace("</trynt>", "");
                //temp
                rsp = rsp.Replace("<cache>true</cache>", "");

                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(rsp);

                movie = (Imdb)Utils.Xml.Deserialize(xmldoc, typeof(Imdb));

                XmlNodeList xmlnodelist = Xml.GetXmlNodeList(xmldoc, "/*/genre/*");
                movie.genre = new string[xmlnodelist.Count];
                for (int i = 0; i < xmlnodelist.Count; i++)
                {
                    movie.genre[i] = xmlnodelist[i].InnerText;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                movie = null;
            }

            return movie;            
        }

        /// <summary>
        /// use web service to get id from imdb
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public static string getImdbId(string title)
        {
            try
            {
                //FIXME: it's necessary convert string title to utf8 encode
                string url = url_webservice + "?t=" + title + "&fo=xml&f=1";
                string rsp = connectUrl(url);

                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(rsp);

                XmlNode xmlnode = xmldoc.SelectSingleNode("/*/movie-imdb/data/movie-id/data/id");

                return xmlnode.FirstChild.Value;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// connect to webservice trynt and get output message
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string connectUrl(string url)
        {
            string response = "";

            WebClient webClient = new WebClient();
            response = webClient.DownloadString(url);

            return response;
        }       

        public static Bitmap LoadPicture(string url)
        {
            HttpWebRequest wreq;
            HttpWebResponse wresp;
            Stream mystream;
            Bitmap bmp;

            bmp = null;
            mystream = null;
            wresp = null;
            try
            {
                wreq = (HttpWebRequest)WebRequest.Create(url);
                wreq.AllowWriteStreamBuffering = true;

                wresp = (HttpWebResponse)wreq.GetResponse();

                if ((mystream = wresp.GetResponseStream()) != null)
                    bmp = new Bitmap(mystream);
            }
            finally
            {
                if (mystream != null)
                    mystream.Close();

                if (wresp != null)
                    wresp.Close();
            }

            return (bmp);
        }
    }
}
